var User =require('../models/user')

exports.showSignup = function(req,res){
	res.render('signup',{
		title:'注册页面'
	})
}

exports.showSignin = function(req,res){
	res.render('signin',{
		title:'登录页面'
	})
}
//signup
exports.signup = function(req,res){
	var _user = req.body.user //通过express body-paser这个中间件获得
	//req.param('user')另一种方法，和上面功能一样的又一个方法，下面的是几个不同的例子
	///user/signup/:userid
	//req.param('userid')
	///user/signup/111?userid=1112
	//var _userid= req.query.userid
	//ajax提交方式,参数都在body里面
	//var _userid= req.body.userid
	User.findOne({name:_user.name},function(err,user){//这里如果用find就逻辑不通，页面跳转不对
		if(err){
			console.log(err)
		}
		if(user){
			res.redirect('/signin')
			console.log('去登录页面，感觉逻辑不完全啊')
		}else{
			var user= new User(_user)
			user.save(function(err,user){
			if(err){
				console.log(err)
			}
			res.redirect('/admin/userlist')
			console.log('去列表页')
			})
			
		}
		
	})
	
}

//signin
exports.signin = function(req,res){
	var _user = req.body.user;
	var name = _user.name;
	var password = _user.password;

	User.findOne({name:name},function(err,user){
		if(err){
			console.log(err);
		}
		if(!user){
			return res.redirect('/signup');
		}else{
			if(password== user.password){
				console.log('password is matched');
				req.session.user=user;
				return res.redirect('/');
			}else{
				return res.redirect('/signin');
				console.log('password is not matched');
			}
		}

		/*user.comparePassword(password,function(err,isMatch){
			if(err){
				console.log(err);
			}

			if(isMatch){
				return res.redirect('/');
				console.log('password is matched');
			}else{
				console.log('password is not matched');
			}
		})*/
	})
}

//logout
exports.logout = function(req,res){
	delete req.session.user
	//delete app.locals.user
	res.redirect('/')
}

//userlist page
exports.userlist = function(req, res){
	User.fetch(function(err, users){//这个fetch 是在shemale里面置自定的函数
		console.log("/admin/userlist   users")
		if (err) {
			console.log(err)
		}
		res.render('userlist',{
		title:'imooc 用户列表页',
		users:users
	})
	})
}

//midware for user
exports.signinRequired = function(req, res,next){
	var user = req.session.user
	if (!user) {
		return res.redirect('/signin')
	}
	next()
}

//midware for user
exports.adminRequired = function(req, res,next){
	var user = req.session.user

	if (user.role<=10) {
		return res.redirect('/signin')
	}
	next()
}

